

package com.surroundyou.dbResources;


import java.sql.*;
import java.sql.DriverManager;
import java.util.ArrayList;

/**
 *
 * @author PKondekar
 */
public class DbConPoolManager{

    private int sizeOfPool = 20;
    private static Object obj = new Object();
    private static ArrayList connPool   = new ArrayList();

    /**
     *
     */
    public DbConPoolManager()
    {
        try
        {
        	Class.forName("com.mysql.jdbc.Driver").newInstance();

            for (int i = 0; i < sizeOfPool; i++)
            {
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/surroundyou","root","root");
                connPool.add(conn);
            }
            

        }
        catch (Exception e)
        {
            System.out.println("Exception in DbconnPool constructor...");
            e.printStackTrace(System.out);
        }


    }

    /**
     *
     * @return
     * @throws java.lang.Exception
     */
    public Connection getConnection() throws Exception
    {

        Connection conn = null;

      //
        if (! connPool.isEmpty())
        {

        	synchronized(obj)
        	{
	        	conn = (Connection)connPool.get(0);
	            connPool.remove(0);
        	}
        }


        return conn;


    }


    /**
     *
     * @param conn
     */
    public void returnConnection(Connection conn)
    {

        if (conn != null)
        {

            connPool.add(conn);
        }

    }

}

